<template>
  <div class="translate">
    <el-dialog :visible.sync="dialogVisible" width="800px" title="分发邮件" center :close-on-click-modal="false"
               :close-on-press-escape='false'>
      <h2>1.选择目标邮箱账户</h2>
      <div class="sidebar-wrapper" style="max-height: 500px;overflow-y: scroll">
        <el-tree
          :data="menuData"
          show-checkbox
          node-key="id"
          ref="tree"
          highlight-current
          :props="defaultProps">
         <span class="custom-tree-node" slot-scope="{ node, data }" :class="{'disItem':data.fileExt !== ''}">
            <span onselectstart="return false">{{node.label}}</span>
            <el-select class="my-email" v-model="data.fileId" @change="onChangeProgram($event,data.id)"
                       v-if="data.hasOwnProperty('list')&&data.list.length>0" placeholder="请选择">
              <el-option v-for="item in data.list"
                         :key="item"
                         :label="item"
                         :value="item">
              </el-option>
            </el-select>
        </span>
        </el-tree>
      </div>
      <h2>2.选择我的邮箱发送</h2>
      <el-select class="email" size="small" v-model="senderEmail">
        <el-option v-for="item in common.emailList" :key="item.emailAddr"
                   :label="item.emailAddr" :value="item.emailAddr"></el-option>
      </el-select>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" size="mini">确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import {getTree, getMailDetail} from '@/api/mail/make'
    import {getDiffList} from '@/util/util'
    import {mapState} from 'vuex'

    export default {
        name: "LabelDialog",
        data() {
            return {
                dialogVisible: false,
                menuData: [],
                addresseeEmail: [],
                senderEmail: '',
                defaultProps: {
                    children: 'children',
                    label: 'value'
                },
                content: {},
                name: ''
            }
        },
        computed: {
            ...mapState(['common'])
        },
        methods: {
            onChangeProgram(email, ID) {
                //获取对应的
                this.addresseeEmail.push({email: email, id: ID})
                this.addresseeEmail.map(item => {
                    if (item.id == ID) {
                        item.email = email;
                    }
                })
            },
            init(temailInfoId, name) {
                console.log(temailInfoId, name)
                this.name = name;
                this.getDetail(temailInfoId);
                this.getTree();
                this.senderEmail = this.common.emailList[0].emailAddr
                this.addresseeEmail = [];
                this.dialogVisible = true;
            },
            getDetail(temailInfoId) {
                getMailDetail(temailInfoId).then(res => {
                    if (res.data.success) {
                        this.content = res.data.data;
                    }
                })
            },
            getTree() {
                getTree().then(res => {
                    if (res.data.success) {
                        this.menuData = res.data.data;
                    }
                }).catch(err => {
                    console.log(err)
                })
            },
            submit() {
                if (this.addresseeEmail.length == 0) {
                    this.$message({
                        type: "success",
                        message: '请选择要分发的用户邮箱'
                    });
                    return;
                }
                const resultArr = this.dealArr(this.addresseeEmail);
                //跳转编辑页面
                this.content.emailContent = `${this.common.sign}` + this.getEndEmail() + this.content.emailContent;
                this.content.addresseeEmail = resultArr.join(',');
                this.content.senderEmail = this.senderEmail;
                this.content.userEmail = this.senderEmail;
                this.content.tEmailInfoIds = '';
                this.content.temailInfoId = '';
                this.content.emailSecretDelivery = '';
                this.content.emailCarbonCopy = '';
                const target = JSON.parse(JSON.stringify(this.content))
                //插入store - 去重
                const ID = target.temailInfoId + "t";
                this.dialogVisible = false;
                let targetName = '',path='',type='';
                if (this.name == 'emailListTab') {//收件箱
                    targetName = 'SET_EMAILLISTTAB';
                    path= '/mail/index';type=0;
                } else if (this.name == 'emailListUnreadTab') {//未读信箱
                    targetName = 'SET_EMAILLISTUNREADTAB';
                    path= '/mail/unread';type=6;
                } else if (this.name == 'emailListOutTab') {//已发送箱
                    targetName = 'SET_EMAILLISTOUTTAB';
                    path= '/mail/send/index';type=3;
                } else if (this.name == 'emailListPendingTab') {//待处理
                    targetName = 'SET_EMAILLISTPENDINGTAB'
                    path= '/mail/pending/index';type=1;
                } else if (this.name == 'emailListCustomerTab') {//客户模式
                    targetName = 'SET_EMAILLISTCUSTOMERTAB';
                    path= '';
                }
                if (getDiffList(ID, this.name) == -1) {
                    this.$store.commit(targetName, {
                        type: 1, row: {
                            id: ID,
                            title: target.emailSubject,
                            state: 2,
                            file: '',
                            info: JSON.stringify(target),
                            close: true
                        }
                    })
                } else {
                    this.$store.commit(targetName, {type: 0, current: ID})
                }
                if(path){//存在
                    if(type){
                        this.$store.commit('SET_ISFRAG', type)
                    }
                    this.$router.push(path)
                }

            },
            getEndEmail() {
                let emailCarbonCopy = this.content.emailCarbonCopy ? this.content.emailCarbonCopy.split(',') : [];//目标抄送数组
                let str = `<br><br><br>---------------- Original ----------------<br><div class="previous" style="color: #000000;font-size: 14px;font-family: Arial;line-height: 1.7;margin-bottom: 20px;background-color: #dddddd45;
    padding: 0 5px;">From: ${this.content.senderEmail}<br>Date: ${this.content.sendTime}<br>To:${this.filterStr(this.content.addresseeEmailArray).join(";")}`;
                if (emailCarbonCopy.length > 0) {
                    let cc = `<br>CC:${this.filterStr(emailCarbonCopy).join(";")}`;
                    str += cc;
                }
                const subject = `<br>Subject: ${this.content.emailSubject}</div>`;
                str += subject;
                return str;
            },
            filterStr(arrOld) {
                let arr = [];
                arrOld.map((item, index) => {
                    if (item.indexOf('<') != -1) {//<1749846095@qq.com>
                        item = item.split('<')[1];
                        item = item.split('>')[0];
                    }
                    arr.push(item);
                })
                return arr;
            },
            dealArr(arr) {
                let newArr = [arr[0]];
                for (let i = 1; i < arr.length; i++) {
                    let repeat = false;
                    for (let j = 0; j < newArr.length; j++) {
                        if (arr[i].id === newArr[j].id) {
                            repeat = true;
                            break;
                        } else {

                        }
                    }
                    if (!repeat) {
                        newArr.push(arr[i]);
                    }
                }
                let end = [];
                newArr.map(item => {
                    end.push(item.email)
                })
                return end;
            },
            nodeClick(value) { // 左键请求子级,根据自建目录和共享目录的字段进行不同的跳转
                console.log(value)
            },
        }
    }
</script>

<style lang="scss">
  .translate {
    h2 {
      color: #000;
      line-height: 45px;
      font-size: 15px;
      text-align: left;
    }

    .el-tree {
      width: calc(100% - 50px);
      margin: 0 25px;
      max-width: calc(100% - 50px);
      min-width: calc(100% - 50px);
      overflow-x: hidden;
    }

    .custom-tree-node {
      font-size: 14px;
    }

    .el-select.my-email {
      float: right;
      padding-right: 30px;
      border: 0;

      .el-input--suffix .el-input__inner {
        border: 0;
        height: 30px;
        line-height: 30px;
      }
    }

    .el-select.email {
      margin-top: 5px;
      margin-left: 30px;
      float: left;
    }
  }

</style>
